/*
 * jngc, Java utility classes by Nicholas Coltharp
 * Copyright (C) 2010 Nicholas Coltharp <ngc1@rice.edu>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.rice.ngc1.util;

import java.io.IOException;
import java.util.Iterator;

/**
 * Contains utility methods for dealing with strings.
 */
public final class Strings {

    /**
     * Private constructor to prevent construction.
     */
    private Strings() {}

    public static String join(Iterable<?> objs, CharSequence sep) {
        StringBuilder builder = new StringBuilder();
        return join(objs, sep, builder).toString();
    }

    public static StringBuilder join(Iterable<?> objs, CharSequence sep,
            StringBuilder builder) {
        try {
            return (StringBuilder) join(objs, sep, (Appendable) builder);
        } catch (IOException e) {
            throw new UnexpectedExceptionException(e);
        }
    }

    public static StringBuffer join(Iterable<?> objs, CharSequence sep,
            StringBuffer buf) {
        try {
            return (StringBuffer) join(objs, sep, (Appendable) buf);
        } catch (IOException e) {
            throw new UnexpectedExceptionException(e);
        }
    }

    public static <T extends Appendable> T join(Iterable<?> objs,
            CharSequence sep, T builder) throws IOException {
        Iterator<?> iter = objs.iterator();
        while (iter.hasNext()) {
            builder.append(iter.next().toString());
            if (iter.hasNext()) {
                builder.append(sep);
            }
        }
        return builder;
    }
}
